package com.example.qihuibao.widget.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.bean.*
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.extension.toast

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/13
 *     desc   :
 */
class DepartmentInfoLayout(ctx:Context) : FrameLayout(ctx) {
    private lateinit var activity:MainActivity
    private lateinit var root:View
    private var modify = false
    private val departmentList = mutableListOf<Department>()
    private lateinit var rv_dep:CommonRecyclerView

    init {
        if (ctx is MainActivity) {
            activity = ctx
        }
        root = LayoutInflater.from(ctx).inflate(R.layout.layout_department, this, true)
        root.setOnClickListener {  }//禁止点击事件穿透
        initView()
    }

    private fun initView() {
        root.findViewById<TextView>(R.id.tv_title).text = "部门信息"
        val tvRight1 = root.findViewById<TextView>(R.id.tv_tv_right1)
        val tvRight2 = root.findViewById<TextView>(R.id.tv_tv_right2)
        val tvRight3 = root.findViewById<TextView>(R.id.tv_tv_right3)
        val tvRight4 = root.findViewById<TextView>(R.id.tv_tv_right4)
        tvRight1.text = "修改"
        tvRight2.text = "更新"
        tvRight3.text = "新增"
        tvRight4.text = "删除"
        tvRight1.visibility = View.VISIBLE
        tvRight2.visibility = View.VISIBLE
        tvRight3.visibility = View.VISIBLE
        tvRight4.visibility = View.VISIBLE
        tvRight1.setOnClickListener {
            modify = !modify
            tvRight1.text = if(modify) "取消" else "修改"
            setModify()
            if (!modify) {
                queryDepartmentInfo()
            }
        }
        tvRight2.setOnClickListener {
            if (modify) {
                update()
            }else {
                activity.toast("先点击修改")
            }
        }
        tvRight3.setOnClickListener {
            if (modify) {
                add()
            }else {
                activity.toast("先点击修改")
            }
        }
        tvRight4.setOnClickListener {
            if (modify) {
                delete()
            }else {
                activity.toast("先点击修改")
            }
        }
        root.findViewById<View>(R.id.iv_back).setOnClickListener { (parent as ViewGroup).removeView(this) }
        queryDepartmentInfo()
    }

    private fun queryDepartmentInfo() {
        activity.getMainViewModel().queryDepartmentInfo().observe(activity) {
            if (it.RetCode == "0") {
                departmentList.clear()
                if (!it.DepList.isNullOrEmpty()) {
                    departmentList.addAll(it.DepList!!)
                }
                rv_dep = root.findViewById<CommonRecyclerView>(R.id.rv_dep)
                rv_dep.init(
                    R.layout.item_department_with_add_delete,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    departmentList,
                    {parent, pos ->
                        if (departmentList.isNotEmpty()) {
                            val et_DepID1 = parent.findViewById<EdittextWithText>(R.id.et_DepID1)
                            val et_DepName1 = parent.findViewById<EdittextWithText>(R.id.et_DepName1)
                            val et_DepID2 = parent.findViewById<EdittextWithText>(R.id.et_DepID2)
                            val et_DepName2 = parent.findViewById<EdittextWithText>(R.id.et_DepName2)
                            et_DepID1.setContentWithModify(departmentList[pos].DepID1) { s -> departmentList[pos].DepID1 = s }
                            et_DepName1.setContentWithModify("${departmentList[pos].DepName1}") { s -> departmentList[pos].DepName1 = s }
                            et_DepID2.setContentWithModify("${departmentList[pos].DepID2}") { s -> departmentList[pos].DepID2 = s }
                            et_DepName2.setContentWithModify("${departmentList[pos].DepName2}") { s -> departmentList[pos].DepName2 = s }
                            et_DepID1.enableContent(modify)
                            et_DepName1.enableContent(modify)
                            et_DepID2.enableContent(modify)
                            et_DepName2.enableContent(modify)
                            if (departmentList[pos].DepID1.isEmpty()) {//empty
                                parent.findViewById<View>(R.id.ll_content).visibility = View.GONE
                                parent.findViewById<View>(R.id.iv_delete).visibility = View.GONE
                                parent.findViewById<View>(R.id.iv_add).visibility = View.VISIBLE
                            }else {
                                parent.findViewById<View>(R.id.ll_content).visibility = View.VISIBLE
                                parent.findViewById<View>(R.id.iv_delete).visibility = if (modify) View.VISIBLE else View.GONE
                                parent.findViewById<View>(R.id.iv_add).visibility = View.GONE
                            }
                            parent.findViewById<View>(R.id.iv_delete).setOnClickListener {
                                departmentList.removeAt(pos)
                                rv_dep.adapter?.notifyDataSetChanged()
                            }
                            parent.findViewById<View>(R.id.iv_add).setOnClickListener {
                                departmentList.add(departmentList.size-1, Department("1", "", "", ""))
                                rv_dep.adapter?.notifyDataSetChanged()
                            }
                        }
                    }
                )
            }
        }
    }

    private fun setModify() {
//        root.findViewById<EdittextWithText>(R.id.et_RemindSmsThreshold)?.enableContent(modify)
//        if (modify) {
//            departmentList.add(Department())
//        }else {
//            if (departmentList.isNotEmpty() && departmentList.last().DepID1.isEmpty()) {
//                departmentList.removeLast()
//            }
//        }
        rv_dep.adapter?.notifyDataSetChanged()
    }

    private fun update() {
        if (departmentList.isNotEmpty() && departmentList.last().DepID1.isEmpty()) {
            departmentList.removeLast()
        }
        val idMap = hashMapOf<String, String>()
        for (item in departmentList) {
            if (idMap[item.DepID1] == null) {
                idMap[item.DepID1] = item.DepName1?:""
            }else {
                activity.toast("ID不能相同")
                return
            }
        }
        for (item in departmentList) {
            val req = ReqUpdateDepartmentInfoBean()
            req.DepID1 = item.DepID1
            req.DepName1 = "${item.DepName1}"
            req.DepID2 = item.DepID2
            req.DepName2 = item.DepName2
            activity.getMainViewModel().updateDepartmentInfo(req).observe(activity) {
                activity.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
                if (modify) {
                    root.findViewById<TextView>(R.id.tv_tv_right1).performClick()
                }
            }
        }
    }

    private fun add() {
        if (departmentList.isNotEmpty() && departmentList.last().DepID1.isEmpty()) {
            departmentList.removeLast()
        }
        if (departmentList.isEmpty()) {
            departmentList.add(Department())
            rv_dep.adapter?.notifyDataSetChanged()
            return
        }
        val idMap = hashMapOf<String, String>()
        for (item in departmentList) {
            if (idMap[item.DepID1] == null) {
                idMap[item.DepID1] = item.DepName1?:""
            }else {
                activity.toast("ID不能相同")
                return
            }
        }
        for (item in departmentList) {
            val req = ReqAddDepartmentInfoBean()
            req.DepID1 = item.DepID1
            req.DepName1 = "${item.DepName1}"
            req.DepID2 = item.DepID2
            req.DepName2 = item.DepName2
            activity.getMainViewModel().addDepartmentInfo(req).observe(activity) {
                activity.toast("${if (it.RetCode == "0") "新增成功" else "新增失败：${it.RetMsg}"}")
                if (modify) {
                    root.findViewById<TextView>(R.id.tv_tv_right1).performClick()
                }
            }
        }
    }

    private fun delete() {
        if (departmentList.isNotEmpty() && departmentList.last().DepID1.isEmpty()) {
            departmentList.removeLast()
        }
        val idMap = hashMapOf<String, String>()
        for (item in departmentList) {
            if (idMap[item.DepID1] == null) {
                idMap[item.DepID1] = item.DepName1?:""
            }else {
                activity.toast("ID不能相同")
                return
            }
        }
        for (item in departmentList) {
            val req = ReqDeleteDepartmentInfoBean()
            req.DepID1 = item.DepID1
            req.DepID2 = item.DepID2
            activity.getMainViewModel().deleteDepartmentInfo(req).observe(activity) {
                activity.toast("${if (it.RetCode == "0") "删除成功" else "删除失败：${it.RetMsg}"}")
                if (modify) {
                    root.findViewById<TextView>(R.id.tv_tv_right1).performClick()
                }
            }
        }
    }
}